.EQU	DT_LIM,	2
.EQU	ORI_INPUT_VOL, 165

	.GLOBAL	AD_BUF0
	.GLOBAL	AD_BUF1
	.GLOBAL AD_BUF2
	.GLOBAL	AD_BUF3
	.GLOBAL	AD_BUF4
	.GLOBAL	AD_BUF5
	.GLOBAL	T_FLAG
	.global	T1
	.global	T2
	.global	DT
	.GLOBAL	ORI_INPUT_VOL
	.SECTION	.YDATA , DATA , YMEMORY
T_FLAG:	.hword 	0		;MAX 2^15 -1= 32767
DT:	.SPACE	2
T1:	.SPACE	2
T2:	.SPACE	2
;ORI_INPUT_VOL:	.SPACE	2
	.SECTION	.XBSS,	BSS,	XMEMORY

AD_BUF0:	.SPACE	2
AD_BUF1:	.SPACE	2
AD_BUF2:	.SPACE	2
AD_BUF3:	.SPACE	2
AD_BUF4:	.SPACE	2
AD_BUF5:	.SPACE	2

.INCLUDE	"p33FJ16GS502.INC"
.INCLUDE	"MACRO.INC"
.GLOBAL	__ADCP0Interrupt
.GLOBAL	__ADCP1Interrupt
.GLOBAL	__ADCP2Interrupt
.GLOBAL	__T1Interrupt
.TEXT

__ADCP0Interrupt:				; AD PAIR 0(AN0,AN1) 
	NOP
	PUSH.S
	BCLR IFS6, #ADCP0IF			; CLEAR PAIR0 INTERRUTP FLAG
	MOVFF	ADCBUF0, AD_BUF0	; I
	MOVFF	ADCBUF1, AD_BUF1	; V
	CALL	FILTER0
	CALL	FILTER1
	;if Current > 1C(XC), go to PID_CC, until voltage >= 4.15V
	;if Voltage > 4.15V, go to PID_CV, until current below 0.03C
	CALL	PID_CALCULATE
	MOVFF	PID_OUT, MDC
/*	
	INC		COUNT
	BTSS	COUNT,#5	
		CALL	CC_END_CHECK
		CLR		COUNT
*/
	;MOVFF #0XFFFF, PORTA
	POP.S
	NOP
	RETFIE

__ADCP1Interrupt:				; AD PAIR 1(AN2,AN3)
	NOP
	PUSH.S
	
	BCLR IFS6, #ADCP1IF			; CLEAR PAIR1 INTERRUPT FLAG
	;--------------------------------
	
	MOVFF	ADCBUF2, AD_BUF2	; I
;	MOVFF	ADCBUF3, AD_BUF3	; V
	CALL 	FILTER2


INPUT_VOL_CHECK:
	MOV		#ORI_COMMAND_V, W6	; ORI - NOW COMMAND_V
	MOV		FIR2_OUT, W7
	CPSLT	W6,W7				; ORI_INPUT_VOL > IN_VOL, THEN SKIP
	;CALL	COMMAND_VIN_DEC_EQU		; INPUT LOW OR EQU = V-- OR V = V
	CALL	COMMAND_VIN_INC
	POP.S						; ORI_INPUT_VOL > IN_VOL, DON'T CARE
	NOP
	RETFIE

__ADCP2Interrupt:				; AD PAIR 2(AN4,AN5) 
	NOP
	PUSH.S
	
	BCLR IFS7, #ADCP2IF			; CLEAR PAIR2 INTERRUPT FLAG
;	MOVFF	ADCBUF4, AD_BUF4	; I
;	MOVFF	ADCBUF5, AD_BUF5	; V
;	CALL 	FILTER4
;	CALL	FILTER5
;	CALL 	PID_CALCULATE_I
;	MOVFF	PID_OUT, MDC		; PUT PID_OUT RESULT INTO MASTER DUTY CYCLE REGISTER(MDC)
		
	POP.S
	NOP
	RETFIE

__T1Interrupt:
	NOP
	PUSH.S
	
	BCLR IFS0, #T1IF	
	MOVFF	ADCBUF4, AD_BUF4	; I
	MOVFF	ADCBUF5, AD_BUF5	; V
	CALL 	FILTER4
	CALL	FILTER5

T_SET:
;	MOVFF	T1,T2
	MOVFF	AD_BUF5, T1
	;MOVFF	FIR5_OUT, T1
	MOV		T1, W6
	MOV		T2, W7
	SUB		W6,W7,W6
	MOV		W6,	DT

;	MOVFF	ERROR_0_V,ERROR_1_V
	MOV		DT, W6
	MOV		#DT_LIM, W7
	CPSLT	W6,W7				; IF DT < DT_LIM, THEN SKIP 
	BSET	T_FLAG,	#0X1		; DT > DT_LIM, T_FLAG 0X1 SET
	;GOTO	T_FLAG_CLR
	CALL	T_TEST
	POP.S
	NOP
	RETFIE
T_FLAG_CLR:
	BCLR	T_FLAG,	#0X1
	POP.S
	NOP
	RETFIE

	.END